package org.arpit;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;


public class HibernateMainAction {

	/**
	 * @param args
	 * 
	 */
	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String execute() {
		try {
			Configuration configuration=new Configuration();
			configuration.configure();
			ServiceRegistry sr= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
			SessionFactory sf=configuration.buildSessionFactory(sr);
			User user1 = new User();
			user1.setUserName(user.userName);
			user1.setUserMessage(user.userMessage);
			//		
			//		User user2=new User();
			//		user2.setUserName("Ankita");
			//		user2.setUserMessage("Hello world from ankita");
			Session ss = sf.openSession();
			ss.beginTransaction();
			ss.save(user1);
			//		ss.save(user2);
			ss.getTransaction().commit();
			ss.close();
		} catch (Exception e) {
			System.out.println("<---Exception--->");
		}
		System.out.println("<---End--->");
		return "success";
	}
	
public String read() {
		
		
		
	Configuration configuration=new Configuration();
	configuration.configure();
	ServiceRegistry sr= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
	SessionFactory sf=configuration.buildSessionFactory(sr);
		

//		User user2=new User();
//		user2.setUserName("Ankita");
//		user2.setUserMessage("Hello world from ankita");
		Session ss=sf.openSession();
		User user1= (User) ss.byId( User.class ).load(1);
		
		user1.setUserMessage("fin....................");
//				
		
		ss.beginTransaction();
		ss.saveOrUpdate(user1);
//		ss.save(user2);
		ss.getTransaction().commit();
		ss.close();
		System.out.println("<---END--->");
		return "success";
	}

@SuppressWarnings("unchecked")
public String list() {
	
	
	
	Configuration configuration=new Configuration();
	configuration.configure();
	ServiceRegistry sr= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
	SessionFactory sf=configuration.buildSessionFactory(sr);

	Session ss=sf.openSession();
	
	List<User> users  = (List<User>) ss.createQuery("from User_table").list();
	for(int i=0; i<users.size(); i++) {
		System.out.println("Usuario: "+users.get(i).getUserName()+". Mensaje: "+users.get(i).getUserMessage());
		System.out.println("<hr>");
	}

	ss.close();
	System.out.println("<---END--->");
	return "success";
}

}
